package utils

import (
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/beego/beego/v2/server/web/context"
	"github.com/dgrijalva/jwt-go/v4"
)

// json web token

// 负载的信息/自定义负载数据
type CustomClaims struct {
	UserId             int64  `json:"user_id"`
	UserName           string `json:"user_name"`
	jwt.StandardClaims        // 内置的参数
}

var SignKey = []byte("2106A")

// 生成凭证
func CreateToke(claims *CustomClaims) (string, error) {
	// 设置jwt有效期
	claims.StandardClaims.ExpiresAt = jwt.NewTime(float64(time.Now().Unix() + 120))
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(SignKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

// 验证凭证
func VerifyToken(ctx *context.Context) bool {
	client_token := ctx.Request.Header.Get("Authorization")
	// 验证token是否为空
	if client_token == "" {
		return false
	}

	client_token_arr := strings.Split(client_token, " ")

	// 验证token格式
	if cnt := strings.Count(client_token_arr[1], "."); cnt != 2 {
		log.Print(client_token_arr[1])
		return false
	}

	token, err := jwt.ParseWithClaims(client_token_arr[1], &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return SignKey, nil
	})

	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		fmt.Println(claims.UserId)
		fmt.Println(claims.UserName)
		// 在请求中、添加参数
		ctx.Input.SetData("user_id", claims.UserId)
		ctx.Input.SetData("username", claims.UserName)
		return true
	} else {
		fmt.Println(err)
		return false
	}
}
